package fid

import (
	"fmt"

	"gitee.com/gaoguangting/fid/session"
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
)

// const SESSION_KEY = "SIV_SESSION"

type SessionConfig struct {
	Provider       string `json:"provider" conf:"provider.name,default(memory)"` //memory,file,mysql,redis etc
	ProviderConfig string `json:"provider_config" conf:"provider.config"`        //memory,file,mysql,redis etc
	CookieName     string `json:"cookieName" conf:"cookiename,default(fiddddddsession)"`
	Gclifetime     int64  `json:"gclifetime" conf:"gclifetime,default(3600)"`
	Maxlifetime    int64  `json:"maxlifetime" conf:"maxlifetime,default(77760000)"`
	CookieLifeTime int    `json:"cookie_lifetime" conf:"cookie.lifetime,omit"`
}

func (f *Fid) Middleware() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) (err error) {
			sess, err := f.sessionManager.SessionStart(c.Response(), c.Request())
			if err != nil {
				logrus.WithField("err", err).Error("session start error")
				c.Error(err)
				return nil
			}
			defer sess.SessionRelease(c.Response())
			// c.Set(SESSION_KEY, sess)
			if err := next(c); err != nil {
				c.Error(err)
			}
			return nil
		}
	}
}

func (f *Fid) sessionStart() error {
	config := &session.ManagerConfig{
		ProviderConfig:  f.config.SessionConfig.ProviderConfig,
		CookieName:      f.config.SessionConfig.CookieName,
		EnableSetCookie: true,
		Gclifetime:      f.config.SessionConfig.Gclifetime,
		Maxlifetime:     f.config.SessionConfig.Maxlifetime,
		CookieLifeTime:  f.config.SessionConfig.CookieLifeTime,
		Secure:          false,
		SessionIDLength: 32,
	}
	var err error
	f.sessionManager, err = session.NewManager(f.config.SessionConfig.Provider, config)
	if err != nil {
		fmt.Println("new session error [%v]", err)
		return err
	}
	go f.sessionManager.GC()
	return nil
}
